<?php


namespace App\Services\Company\Services;

use App\Services\Business\Interfaces\ActivityServiceInterface;
use App\Services\Member\Models\UserRole;
use App\Services\Member\Services\ActivityService;
use App\Services\Company\Interfaces\CompanyServiceInterface;
use App\Services\Company\Models\Company;

use Carbon\Carbon;
use Illuminate\Support\Facades\Auth;


class CompanyService implements CompanyServiceInterface
{



    /**
     * @param int $id
     * @return array
     */
    public function find(int $id,array $with = [])
    {
        return Company::query()->with($with)->where('id', $id)->firstOrFail()->toArray();
    }

    /**
     * @return array
     */
    public function currentCompany(): array
    {
        $user = Auth::user();
        return Company::find($user['login_company_id'])->toArray();
    }


    /**
     * @param int $shopId
     * @param int $inc
     * @return void
     */
    public function balanceInc(int $shopId, int $inc): void
    {
        $shop = Company::find($shopId);
        $shop->balance += $inc;
        $shop->total_balance += $inc;


        $shop->save();
    }

    public function balanceWithdrawalInc(int $shopId, int $inc): void
    {
        Company::find($shopId)->increment('balance',$inc);
    }


    public function getActivities(int $shopId, int $page, int $size)
    {

        /**
         * @var  $activityService   ActivityService
         */
        $activityService = app()->make(ActivityServiceInterface::class);

        $adminIds = UserRole::query()->where('company_id', $shopId)->pluck('id')->toArray();
        $userIds = CompanyAdministrator::query()->whereIn('id', $adminIds)->pluck('app_id')->toArray();

        $activities  =  $activityService->getActivities($userIds,$page,$size);

        return compact('activities');


    }


    /**
     * @param int $shopId
     * @param int $roleId
     * @param string $expiredAt
     */
    public function changeRole(int $shopId, int $roleId, string $expiredAt): void
    {
        Company::whereId($shopId)->update([
            'role_id' => $roleId,
            'expired_at' => Carbon::parse($expiredAt),
        ]);

    }


}
